package com.example.doer.reading.AppActivities;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.ab.activity.AbActivity;
import com.ab.http.AbHttpUtil;
import com.ab.http.AbStringHttpResponseListener;
import com.ab.image.AbImageLoader;
import com.ab.view.pullview.AbPullToRefreshView;
import com.example.doer.reading.AppDataModel.CircleImageView;
import com.example.doer.reading.AppDataModel.Topic;
import com.example.doer.reading.AppDataModel.TopicReply;
import com.example.doer.reading.R;
import com.example.doer.reading.global.MyApplication;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import static com.ab.util.AbToastUtil.showToast;

//import com.example.doer.reading.AppAdapter.TopicReplyListAdapter;

public class TopicWithReplyActivity extends AbActivity {
    private TextView topicName;
    private TextView topicContent;
    private ListView replyListView;
    private List<TopicReply> topicReplyList = new ArrayList<TopicReply>();
    TopicReplyListAdapter topicReplyListAdapter;//适配器
    private AbPullToRefreshView abPullToRefreshView_topicReply=null;
    AbHttpUtil abHttpUtil;
    static int replyCount;
    Topic receivedTopic;//界面跳转接受到的Topic对象
    String UserID;//全局的UserID
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setAbContentView(R.layout.activity_topic_with_reply);
        /**
         * 下滑刷新加载等等
         */
        abPullToRefreshView_topicReply = (AbPullToRefreshView) findViewById(R.id.layout_all);
        topicName = (TextView)findViewById(R.id.nameOfActivityTopicWithReply);
        topicContent = (TextView)findViewById(R.id.contentOfActivityTopicWithReply);
        //获取listView的对象引用
        replyListView = (ListView)findViewById(R.id.topicReplyListView);
        //获取传递的数据
        receivedTopic = (Topic) getIntent().getSerializableExtra("topicObjWithReply");
        topicName.setText(receivedTopic.getTopicName());
        topicContent.setText(receivedTopic.getTopicContent());
        /**
         * 从服务器获取该Question的所有Answer数据  通过Question(Topic对象)
         *
         * 测试时UserID用svip
         *
         */
        UserID = MyApplication.user.getUserID();
        String url = "http://192.168.191.1/Reading/AnswerServlet?Action=down&userID="+UserID+"&QuestID="+receivedTopic.getTopicID();
        abHttpUtil = AbHttpUtil.getInstance(TopicWithReplyActivity.this);
        abHttpUtil.get(url, new AbStringHttpResponseListener() {
            @Override
            public void onSuccess(int i, String s) {//s为获取到的JSON字符串
                try {
                    JSONArray jsonArray = new JSONObject(s).getJSONArray("Answers");
                    for(int j=0;j<jsonArray.length();j++){
                        if(replyCount<10){
                            //只需要显示UserName UserImg AnswerContent FavourCount ReplyCount
                            JSONObject thirdObj = jsonArray.getJSONObject(j);
                            String thirdObjID = thirdObj.getString("AnswerID");
                            String thirdObjFromTopicID = thirdObj.getString("AnswerFromQuestID");
                            String thirdObjContent = thirdObj.getString("AnswerContent");
                            String thirdObjUserName = thirdObj.getString("AnswerFromUserName");
                            String thirdObjUserID = thirdObj.getString("AnswerFromUserID");
                            String thirdObjFavourCount = thirdObj.getString("ThumbUpCount");
                            String thirdObjReplyCount = thirdObj.getString("ReplyCount");
                            String thirdObjCollectCount = thirdObj.getString("UserCollectCount");boolean thirdObjIsThumbUp = thirdObj.getBoolean("IsThumbUp");
                            boolean thirdObjIsCollect = thirdObj.getBoolean("IsCollect");
                            topicReplyList.add(new TopicReply(thirdObjID,thirdObjFromTopicID,thirdObjUserID,thirdObjUserName,thirdObjContent,Integer.valueOf(thirdObjFavourCount),Integer.valueOf(thirdObjCollectCount),Integer.valueOf(thirdObjReplyCount),thirdObjIsThumbUp,thirdObjIsCollect));
                        }//end if(replyCount)<10
                        else break;
                    }//end for
                    replyCount = 0;
                    topicReplyListAdapter = new TopicReplyListAdapter(TopicWithReplyActivity.this,topicReplyList, R.layout.topic_reply_listview);
                    if(topicReplyList.size()!=0)
                        replyListView.setAdapter(topicReplyListAdapter);
                    else{}
                        //replyListView.setEmptyView(findViewById(R.id.topicReplyListView_emptyView));
                }//end try
                catch (JSONException e){replyCount =0;
                    e.printStackTrace();}
            }//end onSuccess
            @Override
            public void onStart() {}
            @Override
            public void onFinish() {}
            @Override
            public void onFailure(int i, String s, Throwable throwable) {
                showToast(TopicWithReplyActivity.this,"服务器请求失败");
            }
        });
        /**
         * 回复Topic话题（第二级) btn
         */
        //返回按钮
        ((TextView)findViewById(R.id.topicWithReplyReturnBtn)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                TopicWithReplyActivity.this.finish();
            }
        });
        /**
         * 回复功能--->传递Topic
         */
        TextView buttonReply = (TextView)findViewById(R.id.btnReplyTopic);
        buttonReply.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //显示界面的方法
                Intent intent = new Intent(TopicWithReplyActivity.this, ReplyWritingActivity.class);
                //传递Topic数据
                intent.putExtra("topicObjForReplyResult",receivedTopic);
                startActivityForResult(intent,1001);
            }
        });
    }//end onCreate method

    /**
     * 为了得到传回的数据，必须在前面的Activity中（指MainActivity类）重写onActivityResult方法
     *
     * requestCode 请求码，即调用startActivityForResult()传递过去的值
     * resultCode 结果码，结果码用于标识返回数据来自哪个新Activity
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        //String result = data.getExtras().getString("result");//得到新Activity 关闭后返回的数据
        //Log.i(TAG, result);
        switch (resultCode){
            case 2001:{//取消
                //无反应
                break;
            }
            case 2002:{
                //确定按钮
                TopicReply theTopicReply = (TopicReply) data.getSerializableExtra("returnReplyObj");
                topicReplyListAdapter.addTopicReply(theTopicReply);
//                String userID = theTopicReply.getUserID();
//                String answerFromQuestID = theTopicReply.getTopicID();
//                String replyCon = theTopicReply.getReplyContent();
//                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//                String date = sdf.format(theTopicReply.getDate());
//                String url = "http://192.168.191.1/Reading/AnswerServlet?Action=up&userID="
//                        +userID+"&answerFromQuestID="+answerFromQuestID+"&answerContent="+replyCon+"&date="+date;
//                abHttpUtil.get(url, new AbStringHttpResponseListener() {
//                    @Override
//                    public void onSuccess(int i, String s) {
//                    }
//                    @Override
//                    public void onStart() {}
//                    @Override
//                    public void onFinish() {}
//                    @Override
//                    public void onFailure(int i, String s, Throwable throwable) {
//                        showToast(TopicWithReplyActivity.this,"连接服务器失败");}
//                });
                break;
            }
            default:
                break;
        }
     }

    class TopicReplyListAdapter extends BaseAdapter {
        List<TopicReply> topicReplyList;
        Activity context;
        int ResID;
        AbImageLoader abImageLoader;
        //回复框  Visibility动态变化
        private LinearLayout myReplyViewLayout;
        private PopupWindow myPopupWindow;//点击回复弹出回复框
//        private int myPopupWindowWidth;
//        private int myPopupWindowHeight;
        private int mScreenWidth;//屏幕的宽度 用于放PopWindow
        public TopicReplyListAdapter(Context theContext, List<TopicReply>theList, int theResID){
            //context赋值 为一个TopicWithReplyActivity
            this.context = (Activity) theContext;
            this.topicReplyList = theList;
            this.ResID = theResID;
            abImageLoader = AbImageLoader.getInstance(TopicWithReplyActivity.this);
        }
        //实现适配器
        @Override
        public int getCount(){
            return topicReplyList.size();
        }
        public TopicReply getItem(int position){
            return topicReplyList.get(position);
        }
        public long getItemId(int position){
            return position;
        }
        public View getView(final int position, View convertView, ViewGroup parent){
            convertView = LayoutInflater.from(context).inflate(ResID,null);
            final TopicReply topicReply = topicReplyList.get(position);

            final String replyUserID = topicReply.getUserID();
            CircleImageView userImageView = (CircleImageView) convertView.findViewById(R.id.userResOfTopicReplyListView);

            TextView userName = (TextView)convertView.findViewById(R.id.userNameOfTopicReplyListView);
            TextView replyContent = (TextView)convertView.findViewById(R.id.replyContentOfTopicReplyListView);
            TextView replyFavourCount = (TextView)convertView.findViewById(R.id.favourCountOfTopicReplyListView);
            TextView replyCommentCount = (TextView)convertView.findViewById(R.id.replyCountOfTopicReplyListView);
            /**
             * 设置用户头像
             */
            String url = "http://192.168.191.1/Reading/ImageDoServlet?Action=download&Category=UserLogo&ImageName="+replyUserID;
            abImageLoader.display(userImageView,url,300,300);
            userName.setText(topicReply.getUserName());

            /**
             * 用户头像点击事件
             */
            userImageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(TopicWithReplyActivity.this,MyHomeActivity.class);
                    intent.putExtra("UserID",replyUserID);
                    startActivity(intent);
                }
            });
            replyContent.setText(topicReply.getReplyContent());
            replyFavourCount.setText("赞 "+String.valueOf(topicReply.getFavoCount()));
            replyCommentCount.setText("回复 "+String.valueOf(topicReply.getReplyCount()));
            replyContent.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    receivedTopic.setaTopicReply(topicReply);
                    Intent intent = new Intent(TopicWithReplyActivity.this,TopicActivity.class);
                    intent.putExtra("topicReplyObj",receivedTopic);
                    startActivity(intent);
                }
            });
            return convertView;
        }//end method getView
        /**
         * 弹出回复框--->转移实现
         */
        private void showMore(View showMoreBtn,final TopicReply theTopicReply){
        //隐藏的水平回复布局
            View view = LayoutInflater.from(TopicWithReplyActivity.this).inflate(R.layout.topic_add_reply,null);
            myReplyViewLayout = (LinearLayout)view.findViewById(R.id.mReplyViewLayout);
            myReplyViewLayout.setBackgroundColor(getResources().getColor(R.color.color_ff));
            Button btnCommit = (Button)view.findViewById(R.id.commitBtn);
            final EditText editText = (EditText)view.findViewById(R.id.review_comment_edit) ;
            editText.setHint("回复： "+theTopicReply.getUserName());
            //CommitBtn的点击事件
            btnCommit.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String s = editText.getText().toString();
                    //输出内容不为空
                    if(!TextUtils.isEmpty(s.trim())){
//                        TopicReply newTopicReply = new TopicReply("测试用户",s);
//                        addTopicReply(newTopicReply);
                        //editText.setText("");
                        myPopupWindow.dismiss();
                    }
                    else
                        Toast.makeText(TopicWithReplyActivity.this,"输入内容不能为空",Toast.LENGTH_SHORT);
                }
            });

            //获取放PopWindow的位置
            //获取屏幕分辨率
            DisplayMetrics metrics = new DisplayMetrics();
            getWindowManager().getDefaultDisplay().getMetrics(metrics);
            mScreenWidth = metrics.widthPixels;
            myPopupWindow = new PopupWindow(view,mScreenWidth,200);
            myPopupWindow.setTouchInterceptor(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    if(event.getAction() == MotionEvent.ACTION_OUTSIDE){
                        myPopupWindow.dismiss();
                    }
                    return false;
                }
            });
            myPopupWindow.setWidth(WindowManager.LayoutParams.MATCH_PARENT);
            myPopupWindow.setHeight(WindowManager.LayoutParams.WRAP_CONTENT);
            myPopupWindow.setTouchable(true);
            myPopupWindow.setFocusable(true);
            myPopupWindow.setOutsideTouchable(true);
            myPopupWindow.setBackgroundDrawable(new BitmapDrawable());
            //从底部出现
            myPopupWindow.setAnimationStyle(R.style.GrowFromBottom);
            myPopupWindow.showAtLocation(findViewById(R.id.layout_all), Gravity.BOTTOM,0,0);
            //获取焦点
            editText.requestFocus();
        }//end method showMore

        public void addTopicReply(TopicReply topicReply){
            topicReplyList.add(topicReply);
            notifyDataSetChanged();
        }
    }//end adapter
}//end class
